<template>
  <view class="apply">
    <swiper class="swiper" :current="currentStep">
      <swiper-item
        class="swiper-item"
        v-for="(card, cIndex) in steps"
        :key="card.title"
        @touchmove.stop.prevent="stopTouchMove"
      >
        <scroll-view class="scroll-view" :scroll-y="true">
          <view :class="{ 'scroll-view-box': cIndex === steps.length - 1 }">
            <view class="card">
              <view class="head">
                {{ card.title }}
              </view>
              <view class="data-list">
                <view
                  class="item"
                  v-for="(item, index) in card.dataList"
                  :key="item.key"
                >
                  <view class="list-item" v-if="!card.edit">
                    <view class="label">{{ item.label }}</view>
                    <view class="value">
                      {{ item.val || item.value }}
                    </view>
                  </view>
                  <block v-else>
                    <view class="input-item" :class="{ first: !index }">
                      <view class="label"
                        >{{ item.label }}

                        <label class="require" v-if="item.require">*</label>
                      </view>
                      <view class="value">
                        <view v-if="item.type === 'template'">
                          <view class="textarea-box">
                            <textarea
                              class="textarea"
                              v-model="dataForm[item.key]"
                              :placeholder="item.placeholder"
                              :max="item.max"
                            ></textarea>

                            <Upload
                              :imgList="dataForm.img"
                              :uploadWidth="146"
                              :uploadHeight="146"
                              :imgCount="3"
                              :custom="true"
                              :edit="true"
                              :showDelete="true"
                              :longDelete="true"
                              @deleteImg="onDeleteImg"
                              @uploadSuccess="uploadSuccess"
                            ></Upload>
                          </view>
                        </view>
                        <v-input
                          class="v-input"
                          :type="item.type || 'text'"
                          v-model="item.value"
                          :data-value="item.value"
                          :disabled="item.disabled"
                          :range="item.range"
                          :val="item.val"
                          :rangeKey="item.rangeKey"
                          :placeholder="item.placeholder || item.label || ''"
                          @chooseLocation="
                            onChooseLocation($event, card, cIndex, item, index)
                          "
                          @change="onChange($event, card, cIndex, item, index)"
                          v-else
                        >
                          <image
                            :src="imgBaseUrlV2 + 'location_em.png'"
                            mode=""
                            v-if="item.key === 'address'"
                            slot="ft"
                            class="address-icon"
                          />
                        </v-input>
                      </view>
                    </view>
                  </block>
                </view>
              </view>
            </view>
          </view>
          <view class="btn-box" :class="{ last: cIndex === steps.length - 1 }">
            <button
              class="btn"
              :class="{ disabled: card.disabled, 'btn-info': card.disabled }"
              @click="onNext(card, cIndex)"
            >
              {{ cIndex === steps.length - 1 ? "提交服务订单" : "下一步" }}
            </button>
          </view>
        </scroll-view>
      </swiper-item>
    </swiper>

    <Message ref="message"></Message>
  </view>
</template>

<script>
import vInput from "@/components/public/input/input";
import { imgBaseUrl, imgBaseUrlV0, imgBaseUrlV2 } from "@/common/config/index";
import Upload from "@/components/public/upload/index";
import Router from "@/common/js/router";
import detailModule from "@/common/mixins/detail-module";

import {
  getEquipmentOptions,
  getEquipmentsList,
  getEquipmentInfo,
} from "@/common/api/equipment.js";
import {
  getServiceProviderOptions,
  getServiceProviderInfo,
  getServiceProviders,
} from "@/common/api/service-provider.js";
import { postServiceOrderRecord } from "@/common/api/service-order-record";

import { mapState } from "vuex";

export default {
  mixins: [detailModule],
  components: {
    vInput,
    Upload,
  },
  computed: {
    ...mapState("User", ["userInfo"]),
  },
  data() {
    return {
      dataForm: {
        serviceProviderName: "",
        servicer_id: "",
        servicer_address: "",
        service_content_id: "",
        service_type: "",
        device_id: "",
        model_no: "",
        no: "",
        address: "",
        desc: "",
        contact_name: "",
        contact_mobile: "",
        img: [],
      },
      imgBaseUrlV2,
      currentStep: 2,
      steps: [
        {
          id: 1,
          title: "服务商信息",
          edit: false,
          disabled: true,
          dataList: [
            {
              key: "servicer_id",
              label: "服务商",
              value: "",
              type: "picker",
              range: [],
              require: true,
              rangeKey: "label",
            },
            {
              key: "servicer_address",
              label: "地址",
              value: "",
              disabled: true,
            },
            {
              key: "service_content_id",
              label: "服务项目",
              value: "",
              type: "picker",
              range: [],
              require: true,
              rangeKey: "label",
            },
            {
              key: "service_type",
              label: "服务类型",
              value: "",
              disabled: true,
            },
          ],
        },
        {
          id: 2,
          title: "设备信息",
          edit: true,
          disabled: true,
          dataList: [
            {
              key: "no",
              label: "设备编号",
              placeholder: "设备编号",
              type: "picker",
              value: "",
              val: "",
              range: [],
              require: true,
              rangeKey: "label",
            },
            {
              // key: "model_no",
              key: "device_type",
              label: "",
              placeholder: "设备类型",
              value: "",
              disabled: true,
            },
            {
              key: "model_no",
              label: "",
              disabled: true,
              placeholder: "设备型号",
              value: "",
            },
          ],
        },
        {
          id: 3,
          title: "客户联系方式",
          edit: true,
          disabled: true,
          dataList: [
            {
              key: "address",
              label: "服务地址",
              placeholder: "服务地址",
              type: "chooseLocation",
              disabled: true,
              require: true,
              value: "",
            },
            {
              key: "contact_name",
              label: "提报人",
              placeholder: "提报人",
              value: "",
            },
            {
              key: "contact_mobile",
              label: "联系电话",
              placeholder: "联系电话",
              value: "",
            },
            {
              key: "desc",
              label: "描述",
              type: "template",
              placeholder: "请输入描述",
              max: 280,
              value: "",
            },
          ],
        },
      ],
      currentStep: 0,
      currentEquipmentLabel: "请选择设备",
    };
  },
  methods: {
    onChooseLocation(e, card, cardIndex, item, index) {
      this.dataForm.address = item.value = e.address;
      card.dataList.splice(index, 1, item);
    },
    onChange(e, card, cardIndex, item, index) {
      if (item.type === "picker") {
        item.value = e;
        let val = undefined;
        val = e;
        let v = item.range[e];
        if (v) {
          item.val = v[item.rangeKey] || v;
        }
        this.steps[cardIndex].dataList.splice(index, 1, item);

        let rangeItem = item.range[e];
        this.dataForm[item.key] = rangeItem.value;
        console.log(rangeItem, "??rangeItem", item);
        if (item.key === "servicer_id") {
          card.dataList[index + 1].value = rangeItem.address;
          card.dataList[3].value = rangeItem.service_type;
          this.getServiceProviderOptions(this.dataForm.servicer_id);
          this.steps.splice(cardIndex, 1, card);
        } else if (item.key === "service_content_id") {
          card.dataList[index + 1].value = rangeItem.service_type;
          this.steps.splice(cardIndex, 1, card);
        } else if (item.key === "device_id") {
          this.dataForm.device_id = rangeItem.value;
          this.getEquipmentsList();
        } else if (item.key === "no") {
          this.dataForm.device_id = rangeItem.id;
          this.getEquipmentsList();
        }
      } else {
        item.value = e;
        this.dataForm[item.key] = e;
        this.steps[cardIndex].dataList.splice(index, 1, item);
      }
      this.computedDisabled();
    },
    onNext() {
		// debugger
      let f = this.dataForm;
      let dataList = this.steps[this.currentStep].dataList;
      let hasNo = dataList.find((i) => {
        if (i.require && !f[i.key]) {
          return 1;
        }
      });
      if (hasNo) {
        return this.message.error(hasNo.label + "不能为空");
      }
      if (this.currentStep < this.steps.length - 1) {
        this.currentStep++;
      } else {
		  // debugger
        uni.showLoading({
          title: "提交中",
        });
        postServiceOrderRecord(f)
          .then((res) => {
            uni.hideLoading();
            if (res.code !== this.$ERR_OK) {
              return uni.showToast({
                title: res.message || "提交失败,请重试",
                duration: 2000,
                icon: "none",
              });
            }
			
            let id = res.data;
            this.$Router.push({
              path: "/pages/service-order-detail/service-order-detail",
              query: {
                id,
              },
            });
            this.showModal({
              title: "提示",
              content: "提交成功,点击返回上一页",
              showCancel: false,
              success: (r) => this.$Router.go(-1),
            });
          })
          .catch((err) => {
            uni.hideLoading();
          });
        // Router.push("/pageA/service/apply/success");
      }
    },
    stopTouchMove() {
      return false;
    },
    onDeleteImg(index) {
      this.dataForm.img.splice(index, 1);
    },
    uploadSuccess(e) {
      this.dataForm.img.push(e.url);
    },
    async initData() {
      this.dataForm.contact_name = this.userInfo.name;
      this.dataForm.contact_mobile = this.userInfo.mobile;
      uni.showLoading({
        title: "加载中",
        mask: false,
      });

      await Promise.all([
        this.getEquipmentsList(),
        this.getServiceProviders(),
        this.getServiceProviderOptions(this.dataForm.servicer_id),
      ])
        .then((res) => {})
        .catch((err) => {});
      this.steps.map((s) => {
        s.dataList.map((i) => {
          // && !i.value
          if (
            i.key &&
            this.dataForm[i.key] !== undefined &&
            this.dataForm[i.key] !== null
          ) {
            i.value = this.dataForm[i.key];
          }
        });
      });
      this.steps = [...this.steps];
      uni.hideLoading();
      console.log(this.dataForm, this.steps, "??? this.steps");
    },
    getEquipmentsList() {
      if (this.userInfo.id) {
        if (this.dataForm.device_id) {
          return getEquipmentInfo({
            id: this.dataForm.device_id,
          })
            .then((res) => {
              if (res.code !== this.$ERR_OK) {
                return;
              }
              let data = res.data || {};
              if (data) {
                this.dataForm.device_name = this.currentEquipmentLabel =
                  data.device_name;
                this.dataForm.no = data.no;
                this.dataForm.model_no = data.model_no;

                this.steps.map((i) => {
                  i.dataList.map((c, cIndex) => {
                    if (c.key === "model_no") {
                      c.value = data.no;
                    }
                    if (this.$Route.query.device_id) {
                      if (c.key === "no") {
                        c.range = [data];
                        // c.val = data.no;
                      }
                    }
                  });
                });
              }
            })
            .catch((err) => {});
        } else {
          return getEquipmentsList({
            // id: this.dataForm.device_id,
            limit: 9999,
          }).then((res) => {
            let data = res.data || {};
            data = data.data || [];
            data.forEach((i) => {
              i.label = i.device_name;
              i.value = i.id;
            });
            let item = data.find((i) => i.id == this.dataForm.device_id);
            if (item) {
              this.dataForm.device_name = this.currentEquipmentLabel =
                item.label;
            }
            this.steps[1].dataList[0].range = data;
            console.log(item, "??item", data);
          });
        }
      }
    },
    getServiceProviders() {
      if (this.userInfo.id) {
        if (this.dataForm.servicer_id) {
          return getServiceProviderInfo({
            id: this.dataForm.servicer_id,
          })
            .then((res) => {
              if (res.code !== this.$ERR_OK) {
                return this.message.error(res.message || "获取失败");
              }
              let data = res.data;
              console.log(data, "??data");
              data = {
                ...data,
                label: data.name,
                value: data.id,
              };
              if (data) {
                this.dataForm.serviceProviderName = this.serviceProviderLabel =
                  data.name;
                this.dataForm.servicer_address = data.address;
                this.dataForm.servicer_id = data.id;
                this.steps.map((i) => {
                  i.dataList.map((c, cIndex) => {
                    if (c.key === "servicer_id") {
                      c.range = [data];
                      c.value = data ? data.name : "";
                    }
                  });
                });
                this.getServiceProviderOptions(data.id);
              }
            })
            .catch((err) => {});
        }
        return getServiceProviders({
          sort: this.serviceSort || 0,
        }).then((res) => {
          let data = res.data || {};
          let { list = [] } = data;
          let tmp;
          list = list.map((i) => {
            if (
              this.dataForm.servicer_id &&
              i.id == this.dataForm.servicer_id
            ) {
              tmp = i;
            }
            return {
              ...i,
              label: i.name,
              value: i.id,
              address: i.address,
            };
          });
          if (tmp) {
            this.dataForm.service_type = this.serviceProviderLabel = tmp.name;
          }
          this.steps.map((i) => {
            i.dataList.map((c) => {
              if (c.key === "servicer_id") {
                c.range = list;
                c.value = tmp ? tmp.name : "";
              }
            });
          });
          this.serviceProviderOptions = list;
        });
      }
    },
    getServiceProviderOptions(id) {
      if (!id) return;
      return getServiceProviderOptions({
        id: id || "",
      })
        .then((res) => {
          let data = res.data || [];
          let tmp;
          data.forEach((i) => {
            if (
              this.dataForm.serviceProjectId &&
              i.id == this.dataForm.serviceProjectId
            ) {
              tmp = i;
            }
            i.label = i.title;
            i.value = i.id;
          });
          if (tmp) {
            this.dataForm.service_content_id = tmp.id;
          }
          this.steps.map((i) => {
            i.dataList.map((c) => {
              if (c.key === "service_type") {
                c.value = tmp ? tmp.id : "";
                c.val = tmp ? tmp.title : "";
              }
              if (c.key === "service_content_id") {
                c.val = tmp ? tmp.service_type : "";
                c.range = data;
              }
            });
          });
          // this.steps = this.steps.slice(0);
          uni.hideLoading();
        })
        .catch((err) => {
          uni.hideLoading();
        });
    },
    computedDisabled() {
      let c = this.currentStep;
      let item = this.steps[c];
      let n = this.dataForm;
      console.log("??chage", item.dataList, n);
      item.disabled = !!item.dataList.find((i) => {
        if (
          i.require &&
          (n[i.key] === undefined || n[i.key] === null || n[i.key] === "")
        )
          return 1;
      });
      this.steps.splice(c, 1, item);
    },
  },
  async onLoad(q) {
    console.log(q, "??q");
    if (q.serviceProjectId && q.servicer_id) {
      this.dataForm.serviceProjectId = this.dataForm.service_content_id =
        q.serviceProjectId;
      let s1 = this.steps[0];
      s1.dataList[0].key = "serviceProviderName";
      s1.dataList[1].key = "servicer_address";
      this.dataForm["servicer_id"] = q.servicer_id;
    } else {
      this.steps[1].edit = false;
      this.steps[1].dataList.map((i, index) => {
        if (!i.label) {
          i.label = i.placeholder;
        }
        if (!index) {
          // i.key = "device_name";
        }
      });
      let i0 = this.steps[0];
      i0.edit = true;
      this.steps.splice(0, 1);
      this.steps.splice(1, 0, i0);
      this.dataForm.device_id = q.device_id;
    }
    await this.initData();
    console.log(this.steps, "? this.steps");
    let tmpLabel = this.currentEquipmentLabel;
    uni.setNavigationBarTitle({
      title:
        "服务申请" +
        (tmpLabel && tmpLabel !== "请选择设备" ? "-" + tmpLabel : ""),
    });
  },
  watch: {
    dataForm: {
      handler: function (n) {
        this.$nextTick(() => {
          this.computedDisabled();
        });
      },
      deep: true,
    },
  },
};
</script>

<style lang="stylus" scoped>
@import '~@/common/stylus/variable';

.apply {
  background: linear-gradient(180deg, #0d1523 0%, #102945 100%);
  padding-bottom: 1rpx;
}

.card {
  background: #1A3156;
  margin: 30rpx 24rpx;
  padding: 0 20rpx;
  border-radius: 10rpx;
  color:color-white;

  >.head {
    padding: 30rpx 0 18rpx;
    font-size: 36rpx;
    line-height: 56rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 600;
  }
}

.item {
  &:last-child {
    padding-bottom: 24rpx;
  }
}

.address-icon {
  width: 40rpx;
  height: 40rpx;
}

.list-item {
  display: flex;
  padding: 8rpx 0;
  line-height: 42rpx;

  >.label {
    flex: 0 0 4em;
    font-size: 30rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: color-white;
    border: none;
    padding: 0;
    line-height: 42rpx;
    margin-right: 16rpx;
  }

  >.value {
    flex: 1;
    font-size: 30rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
  }
}

.input-item {
  margin-top: 20rpx;

  &.first {
    margin-top: 0;
  }

  >.label {
    border: none;
    font-size: 30rpx;
    line-height: 50rpx;
    font-family: PingFangSC-Regular, PingFang SC;
    font-weight: 400;
    color: color-white;
    padding: 0;
  }

  >.value {
    margin-top: 20rpx;
  }
}

.swiper, .scroll-view {
  height: calc(100vh - var(--window-top) + 1rpx);

  &-item {
    padding-top: 1rpx;
  }
}

.scroll-view-box {
  padding-bottom: 120rpx;
}

.btn-box {
  padding: 24rpx;

  >.btn {
    background: color-active;
    color: #fff;
  }

  &.last {
    position: fixed;
    z-index: 3;
    width: 100%;
    bottom: 0;
  }
}

.textarea-box {
  background: #1A3156;
  padding: 24rpx 24rpx 0;
  color:#fff;
  .textarea {
    height: 190rpx;
	color:#fff;
  }
}
</style>